;
(function () {
  new Vue({
    el: '#contract-list',
    data: {
      quanxian: JSON.parse(window.localStorage.getItem('permissions')), //权限
      contract: {}, // 合同列表数据
      customer: '', // 信息搜索
			// tenantIds: ['105','74','68', '86','107','103','275','88','15','2','48','96','37','100','30','64', '1','11','83'],
      rperson: {
        ids: [],
        name: null,
        list: []
      }, // 对接人
      policysData: [], //策略权限
      listMenu: [
        {
          'name': '草稿',
          'code': 'CG'
        },
        {
          'name': '审批中',
          'code': 'WA'
        },
        {
          'name': '已审核',
          'code': 'PA'
        },
        {
          'name': '审核拒绝',
          'code': 'RJ'
        },
        {
          'name': '执行中',
          'code': 'EX'
        },
        {
          'name': '已作废',
          'code': 'GC'
        },
        {
          'name': '已终止',
          'code': 'TE'
        },
        {
          'name': '已到期',
          'code': 'FN'
        },
        {
          'name': '已结束',
          'code': 'EN'
        }
      ],
      selectedListMenuCode: [],
      currentPage: 1,
      totalPage: 0,
      totalCount: 0,
      limit: ['10'],
      pageLimits: [{ name: '10', code: '10' }, { name: '15', code: '15' }, { name: '20', code: '20' }],
      beginDate: null,
      endDate: null,
      auditStateFlag: false, // 审核状态标记
      proId: '', // 项目ID
      isShowSubmitLayer: false,
      submitLayerData: {
        companyName: '',
        beginDate: '',
        endDate: '',
        id: ''
      },
      columns: '#', // 排序的列
      orders: 'ASC', // 排序方式
      rankType:'',
      tbTitleWidth: { width: 0 + 'px' },
      tbTotalWidth: { width: 957 + 'px' },
      tbOperateWidth: 123,
      tbTitle: [],
      wzTableTitle: [],
      jdTableTitle: [],
      pzTableTitle: [],
      sortTableTitle: [],
      hasCustomConfig: 'N',
      configType: 'JD',
      isShowTableType: false,
      isShowTableLayer: false,
      curModule: 'GWHT',
      tableType: 'scroll',   //  scroll滑动表  fixed固定表
      isScroll: false
    },
    filters: {
      formatDate: function (time) {
        if (time === undefined) return '--'
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
      auditState: function (item) {
        if (item === '全部') return '#'
        return hlCodeConvert.contractAuditState(item)
      },
      formatUndefined: function (item) {
        if (!item) return '--'
        return item
      },
      formatNum: function (item) {
        if (item === undefined) return '--'
        return hlNumberUtil.formatNum(item)
      }
    },
    methods: {
      selectMenuList() {
        this.currentPage = 1
        this.search()
      },
      //合同终止前的校验
      checkClose(id) {
        var that = this
        hlhttp.get({
          url: 'contract/_close/_check',
          data: {
            'contract_id': id
          },
          success: function (res) {
            that.goToEnd(id)
          },
        })
      },
      //前往合同终止页面
      goToEnd(id) {
        hlUrlUtil.goTo('contractNewDeatil', {
          ddtab: true,
          id: id,
          type: 'contractEnd',
          page: 'wpContractList',
        }, true)
      },
      resetTabbar() {
        this.selectedListMenuCode = []
        this.currentPage = 1
        this.search()
      },
      //续租
      createRelet(item) {
        sessionStorage.clear()
        hlUrlUtil.goTo('contractNew1', {
          ddtab: true,
					relet: true,
					id: item.id,
					m_code: item.mCode
        }, true)
      },
      //获取租户的数据访问策略
      policys: function () {
        var _this = this;
        hlhttp.get({
          url: 'data_policys',
          success: function (res) {
            _this.policysData = res
          }
        })
      },
      //输入对接人进行搜索
      onInputDJR: function (e) {
        if (!this.rperson.name) {
          if (!e.data) return;
          this.rperson.name = e.data;
        }
        this.getDataGroup()
      },
      //判断有没有ids
      ifrpersonIds: function () {
        if (!this.rperson.ids.length) {
          this.rperson.name = null
        }
      },
      //搜索负责人工作组组员列表
      getDataGroup: function () {
        var _this = this;
        _this.rperson.ids = [];
        hlhttp.get({
          url: 'data_group/users/_search',
          data: {
            keyword: _this.rperson.name || '#'
          },
          success: function (res) {
            _this.rperson.list = res;
            for (var i = 0; i < _this.rperson.list.length; i++) {
              if (_this.rperson.name.match(res[i])) {
                _this.rperson.ids.push(res[i].userId)
              }
            }
          }
        })
      },
      //设置对接人name，获取id
      setRperson: function (name, id) {
        this.rperson.ids = [];
        this.rperson.name = name;
        this.rperson.ids.push(id)
      },
      // 查询合同
      search: function () {
        var self = this;
        var data = {
          customer: self.customer.trim() || '#',
          begin_date: self.beginDate ? self.beginDate + ' 00:00:00' : '#',
          end_date: self.endDate ? self.endDate + ' 23:59:59' : '#',
          project_ids: self.proId,
          audit_state: self.selectedListMenuCode.length ? self.selectedListMenuCode.join() : '#',
          page: self.currentPage,
          limit: self.limit[0],
          rperson_ids: self.rperson.ids.toString() || '#',
          columns: self.columns,
          orders: self.orders,
          type: 'WR'
        }

        hlhttp.get({
          url: 'tenant/contracts/_search',
          data: data,
          success: function (data) {
            data.contracts.map(item => {
              item.flag = false;
              if (item.auditState == 'EX' || item.auditState == 'PA' || (item.auditState == 'FN'? (item.withdrawFlag == 'N' && item.oldRenewFlag == 'N' ):false)) {
                item.flag = true
              }
            })

            self.contract = data
            self.totalCount = data.totalCount
            self.totalPage = data.totalPage

            loginPrem.loginList()
            self.getHeadConfig()
          }
        })
      },
      // 按签订时间排序
      sortBySTTime: function (item, index) {
        if (item.isSort == 'N') {
          return;
        } else {
          this.rankType = item.value
          if (item.value == 'signTime') {
            this.columns = 'ST'
          }
          if (item.value == 'beginDate') {
            this.columns = 'BD'
          }
          if (item.value == 'endDate') {
            this.columns = 'ED'
          }
        }
        this.orders = this.orders == '#' ? 'ASC' : (this.orders == 'DESC' ? 'ASC' : 'DESC')
        this.search()
      },
      // 重置
      reset: function () {
        this.currentPage = 1
        this.customer = ''
        this.beginDate = null
        this.endDate = null
        this.rperson = {
          ids: [],
          name: null,
          list: []
        };
        this.search()
      },
      // 初始化项目 默认加载所有的项目数据
      initProgrammer: function () {
        var self = this;
        getProduct(
          function (arr) {
            self.proId = arr[1].join(',') || '#'
            self.search()
          },
          function (arr) {
            self.proId = arr[0].join(',') || '#'
            self.search()
          },
          function (arr) {
            self.proId = arr[0].join(',') || '#'
            self.search()
          }
        )
      },
      // 分页
      updateLimit: function (arr) {
        this.limit = [arr[0].code];
        this.currentPage = 1;
        this.search()
      },
      // 新建合同
      createContract: function () {
        var arr = [
          'CREATED_CONTRACT_FIRST_STEP',
          'CREATED_CONTRACT_SECOND_STEP',
          'RENT_ST_POSITION_MES',
          'RENT_WP_POSITION_MES',
          'RENT_BU_UNIT_MES',
          'RENT_UNIT_MES'
        ]
        hlStorage.ssClearMultipleKey(arr)
        hlUrlUtil.goTo('contractNew1', { ddtab: true }, true)
      },
      // 提交合同 合同由草稿变为待审核状态
      submitContract: function (customer, beginDate, endDate, id, pid) {
        var is = this;
        hlhttp.put({
          url: 'bpm/check_project_use',
          data: {
            bpm_key: 'CT',
            project_id: pid
          },
          success: function (res) {
            if (res.flag == 'N') {
              hl.toast('请先配置流程')
              return
            }
            var obj = {
              companyName: customer,
              beginDate: hlDateUtil.formatUTCDate(beginDate, 'yyyy-MM-dd'),
              endDate: hlDateUtil.formatUTCDate(endDate, 'yyyy-MM-dd'),
              id: id
            }
            is.$set(is.$data, 'submitLayerData', obj)
            is.isShowSubmitLayer = true;
          }
        })

      },
      confirmSubmitContract: function () {
        var self = this;
        self.isShowSubmitLayer = false;
        hlhttp.put({
          url: 'contract/wa',
          data: {
            contract_id: self.submitLayerData.id
          },
          success: function (data) {
            self.isShowSubmitLayer = false;
            self.search()
          }
        })
      },
      closeSubmitLayer: function () {
        this.isShowSubmitLayer = false;
      },
      showProjectQM: function (i, val) {
        if (val) hllayer.tips($($('.projectName')[i]), val)
      },
      showCustomerQM: function (i, val) {
        if (val) hllayer.tips($($('.customerName')[i]), val)
      },
      hideQM: function () {
        hllayer.closeall()
      },
      updateContract: function (id) {
        var self = this;
        hlhttp.get({
          url: 'contract/alter_code',
          data: {
            'contract_id': id
          },
          success: function (data) {
            var codeData = data.code;
            if (data.editFlag === 'true') {
              hlUrlUtil.goTo('contractUpdateDetails', {
                contractId: id,
                id: data.alterId,
                ddtab: true
              }, true)
            }
            if (data.editFlag === 'false') {
              hlUrlUtil.goTo('contractChangeIndex', { 'id': id, 'code': codeData, 'ddtab': true }, true)
            }
          }
        })
      },
      // 对应表头字段表宽度值
      getThWidth(val) {
        var res = 70;
        switch (val) {
          case '序':
            res = '40'
            break;
          case '合同编号':
            res = '80'
            break;
          case '合同名称':
            res = '120'
            break;
          case '项目名':
            res = '120'
            break;
          case '客户':
            res = '90'
            break;
          case '签订时间':
            res = '90'
            break;
          case '记租时间':
            res = '90'
            break;
          case '到期时间':
            res = '90'
            break;
          case '状态':
            res = '70'
            break;
          case '工位个数':
            res = '90'
            break;
          case '对接人':
            res = '70'
            break;
          default:
        }
        return res;
      },
      // 对应表头字段是否排序
      getThSort(val) {
        var res;
        switch (val) {
          case '序':
            res = 'N'
            break;
          case '合同编号':
            res = 'N'
            break;
          case '合同名称':
            res = 'N'
            break;
          case '项目名':
            res = 'N'
            break;
          case '客户':
            res = 'N'
            break;
          case '签订日期':
            res = 'Y'
            break;
          case '记租时间':
            res = 'Y'
            break;
          case '到期时间':
            res = 'Y'
            break;
          case '状态':
            res = 'N'
            break;
          case '工位个数':
            res = 'N'
            break;
          case '对接人':
            res = 'N'
            break;
          case '联系人':
            res = 'N'
            break;
          default:
        }
        return res;
      },
      // 获取自定义表头配置
      getHeadConfig() {
        var self = this;
        hlhttp.get({
          url: 'contract/column_header_config',
          data: { 'module': self.curModule },
          success: function (data) {
            var wzTableTitle = [];
            data.systemConfig.forEach((el, i) => {
              var obj = {};
              el['width'] = self.getThWidth(el.name)
              el['isSort'] = self.getThSort(el.name)
              obj = JSON.parse(JSON.stringify(el))
              obj['isShow'] = 'Y'
              wzTableTitle.push(obj)
            })

            data.customConfig.forEach(el => {
              var obj = {};
              el['width'] = self.getThWidth(el.name)
              el['isSort'] = self.getThSort(el.name)
              el['isActive'] = 'N'
            })

            self.wzTableTitle = wzTableTitle;
            self.jdTableTitle = data.systemConfig;
            self.pzTableTitle = data.customConfig;
            self.sortTableTitle = JSON.parse(JSON.stringify(data.customConfig))
            self.hasCustomConfig = data.hasCustomConfig;
            self.configType = data.configType;
            self.refreshTableData()
          }
        })
      },
      // 计算表格标题栏宽度
      calTbTitleWidth() {
        var self = this, width = 4;
        self.tbTitle.forEach(el => {
          if (el.isShow == 'Y') width += Number(el.width);
        })
        return width
      },
      // 计算表格外容器宽度
      calTbWidth() {
        var width = this.calTbTitleWidth() + 124;
        return width > 957 ? 957 : width
      },
      // 刷新当前表格
      refreshTableData() {
        var self = this;

        if (self.configType == 'JD') self.tbTitle = self.jdTableTitle;
        if (self.configType == 'WZ') self.tbTitle = self.wzTableTitle;
        if (self.configType == 'PZ') self.tbTitle = self.pzTableTitle;
        const tbTitleWidth = self.calTbTitleWidth();
        self.tbTitleWidth = { width: tbTitleWidth < 839 ? '100%' : tbTitleWidth + 'px' };
        self.tbTotalWidth = { width: self.calTbWidth() + 'px' };
        // 根据表格title总宽度 来判断当前显示哪种表格类型
        if (tbTitleWidth > 833) self.tableType = 'scroll';
        if (tbTitleWidth <= 833) self.tableType = 'fixed';
      },
      showScroll() {
        this.isScroll = true;
      },
      hideScroll() {
        this.isScroll = false;
      },
      // 保存当前所选表格类型
      saveTableType(type) {
        var self = this;
        hlhttp.post({
          url: 'contract/column_header_select',
          data: { 'module': 'ZZHT', 'config_type': type },
          success: function (data) {
            self.refreshTableData()
          }
        })
      },
      // 保存当前表头
      saveTableTitle(data, isLayer) {
        var self = this;
        function dataWrap(data) {
          var res = [];
          data.forEach((el, i) => {
            res.push({
              'id': el.id,
              'name': el.name,
              'display_name': el.displayName ? el.displayName : '#',
              'value': el.value,
              'is_show': el.isShow,
              'seq': (i + 1).toString()
            })
          })
          return res;
        }

        hlhttp.post({
          url: 'contract/column_header_config',
          data: { 'module': self.curModule, 'has_custom_config': self.hasCustomConfig, 'custom_config': JSON.stringify(dataWrap(data)) },
          success: function (res) {
            if (isLayer) {
              hl.toast('保存成功')
              self.pzTableTitle = JSON.parse(JSON.stringify(data));
              self.isShowTableLayer = false;
              self.refreshTableData()
            }

          }
        })

      },
      selectTableType(type) {
        var self = this;
        if (type == 'JD') {
          self.configType = 'JD'
          self.saveTableType(type);
          return;
        }
        if (type == 'WZ') {
          self.configType = 'WZ'
          self.saveTableType(type);
          return;
        }
        if (type == 'PZ') {
          self.configType = 'PZ'
          self.saveTableType(type);
          // 如果当前自定义表没有配置过 则强制保存完整表头数据
          if (self.hasCustomConfig == 'N') self.saveTableTitle(self.wzTableTitle)
          return;
        }
      },
      showTableTypeComponents() {
        this.isShowTableType = true;
      },
      hideTableTypeComponents() {
        this.isShowTableType = false;
      },
      showTableLayer() {
        this.isShowTableLayer = true;
      },
      closeTableLayer() {
        this.isShowTableLayer = false;
      },
      showhighLightTitleItem(el, i) {
        var self = this;
        this.$set(self.sortTableTitle[i], 'isActive', 'Y')
      },
      removehighLightTitleItem(el, i) {
        var self = this;
        this.$set(self.sortTableTitle[i], 'isActive', 'N')
      },
      selectedTitleItem(el, i) {
        var self = this;
        this.$set(self.sortTableTitle[i], 'isShow', 'Y')
      },
      cancelSelectedTitleItem(el, i) {
        var self = this;
        this.$set(self.sortTableTitle[i], 'isShow', 'N')
      },
      // 确定提交自定义表格
      confirmSubmitTable() {
        var self = this;
        self.saveTableTitle(self.sortTableTitle, true)
      },
      // 初始化拖动排序
      initSortable() {
        const self = this;
        const el = document.getElementById('sortableTable');
        Sortable.create(el, {
          draggable: 'ul',
          onEnd(evt) {
            const beginIndex = evt.oldIndex;
            const endIndex = evt.newIndex;
            const newArr = JSON.parse(JSON.stringify(self.sortTableTitle));
            newArr.splice(endIndex, 0, newArr.splice(beginIndex, 1)[0])
            self.sortTableTitle = [];
            self.$nextTick(() => {
              self.sortTableTitle = newArr
            })
          }
        })
      }
    },
    mounted: function () {
      var self = this;
      hlSelectUi(true)
      var keyArr = ['draftID', 'totalArea', 'contractIsBackEdit', 'contractExpMes', 'unitIDS', 'proName']
      hlStorage.lsClearMultipleKey(keyArr)
      this.initProgrammer()
      this.policys()
      this.initSortable()
      this.getHeadConfig()

      $(document.body).click(function (event) {
        self.rperson.list = [];
      });
    }
  })

}())
